package priv.stones.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/9/26 10:24
 */
class Student {
    private String age;

    public Student() {
    }

    public Student(String name, int age) {
        System.out.println("name:" + name + "  age:" + age);
    }

    public void Say(String str) {

        System.out.println("output :" + str);
    }

    public String convertUpper(String string) {
        return string.toUpperCase();
    }

    public static String OutPut(String string) {
        return "output :" + string;
    }

}


public class Reflect4 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class cls = Class.forName("priv.stones.reflect.Student");

        //调用有参构造器
        Constructor cons = cls.getConstructor(String.class, int.class);
        Student student = (Student) cons.newInstance("str", 50);
        student.Say("some");

        //调用方法
        Object obj = cls.newInstance();
        Method method = cls.getMethod("Say", String.class);
        method.invoke(obj, "test method");
        method = cls.getMethod("convertUpper", String.class);
        System.out.println(method.invoke(obj, "asdfasdf"));
        method = cls.getMethod("OutPut", String.class);
        System.out.println(method.invoke(obj, "test static fun"));

        //调用属性
        Field field = cls.getDeclaredField("age");
        field.setAccessible(true);      //取消封装   相当于取消private
        field.set(obj, "age");
        System.out.println(field.get(obj));

    }

}
